from django.apps import AppConfig


class GrainConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "grain"


class HierarchicalForecastingConfig(AppConfig):
    """分层时间序列预测应用配置"""

    default_auto_field = 'django.db.models.BigAutoField'
    name = 'hierarchical_forecasting'
    verbose_name = '分层时间序列预测'

    def ready(self):
        """应用准备就绪时的初始化操作"""
        # 导入信号处理器
        # import hierarchical_forecasting.signals

        # 初始化默认层级结构配置
        self._initialize_default_hierarchy()

    def _initialize_default_hierarchy(self):
        """初始化默认的层级结构配置"""
        try:
            from .models import HierarchicalStructure

            # 检查是否已存在默认配置
            if not HierarchicalStructure.objects.filter(is_default=True).exists():
                # 创建默认的中国区域层级结构
                default_hierarchy = {
                    "regions": {
                        "华北地区": ["北京市", "河北+天津", "山西省", "内蒙古自治区"],
                        "东北地区": ["辽宁省", "吉林省", "黑龙江省"],
                        "华东地区": ["上海市", "江苏省", "浙江省", "安徽省", "福建省", "江西省", "山东省"],
                        "华中地区": ["河南省", "湖北省", "湖南省"],
                        "华南地区": ["广东+海南", "广西壮族自治区"],
                        "西南地区": ["四川+重庆", "贵州省", "云南省", "西藏自治区"],
                        "西北地区": ["陕西省", "甘肃省", "青海省", "宁夏回族自治区", "新疆维吾尔自治区"]
                    },
                    "levels": ["national", "regional", "provincial"],
                    "description": "中国七大地理区域划分"
                }

                HierarchicalStructure.objects.create(
                    name="中国区域层级结构",
                    description="基于中国七大地理区域的层级结构配置",
                    hierarchy_config=default_hierarchy,
                    is_default=True
                )

        except Exception as e:
            # 在应用初始化阶段，数据库可能还未准备好，忽略错误
            pass
